/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var aeRequest;
var action;
var ajxUrl= "";
var CateArr = new Array();
var id;
var username;
var password;
var fullname;
var address;
var email;
var phone;
var userId;
var IdArr = new Array();
var compound = /^[0-9\s]+$/gi;
var rowId;
var flag;
var rowCount;

function createArray() {
	jQuery("#tblCategory>tbody>tr>td:nth-child(2)").each(function() {
		CateArr.push(jQuery(this).html());
	});
}
function createArrayId() {
	jQuery("#tblLink>tbody>tr>td:nth-child(1)").each(function() {
		CateArr.push(jQuery(this).html());
	});
}
function createXmlHttpRequestObject() {
    var ro;
    var browser = navigator.appName;
    // Need to determine IE7 and not do this.
    if (browser == "Microsoft Internet Explorer") {
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else {
        ro = new XMLHttpRequest();
    }
    return ro;
}

function createResponseXML(textXML) {
    // code for IE
    if (window.ActiveXObject) {
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(textXML);
        return xmlDoc;
    }
    // code for Mozilla, Firefox, Opera, etc.
    else {
        var parser = new DOMParser();
        var xmlDoc = parser.parseFromString(textXML, "text/xml");
        return xmlDoc;
    }
}

function updateUser(userId,username,password,fullname,address,email,phone,action){
    var url = '/Alluring_Decors-war/UserServlet?id='+ userId +'&userName=' +username + '&password=' + password +
                '&fullName=' + fullname + '&address=' + address + '&email=' + email + '&phone=' + phone +
                '&action=' + action;
    //alert(url);
    aeRequest = createXmlHttpRequestObject();
    aeRequest.open("POST", url, true);
    aeRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    aeRequest.onreadystatechange = finishUpdate;
    aeRequest.send(null);
}

function finishUpdate(){
    if(aeRequest.readyState==4){
        if(aeRequest.status == 200){
            var response = createResponseXML(aeRequest.responseText);
            var result = response.getElementsByTagName("result")[0].firstChild.nodeValue;
            if (result == "success") {
                //alert("update/edit successful");
            }else{
                //alert("update/edit failed");
            }
        }
    }
}

function setEditFormPosition(ele){
    var pos = jQuery("#"+ele).position();
	jQuery("#editContainer").css({
		position : "absolute",
		top : pos.top + 18 + "px",
		left : pos.left - 885 + "px"
	});
}

function setDeleteFormPosition(){
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = jQuery("#deleteContainer").height();
	var popupWidth = jQuery("#deleteContainer").width();

	jQuery("#deleteContainer").css({
		"position" : "absolute",
		"top" : (windowHeight/2 - popupHeight/2)-50,
		"left" : (windowWidth/2 - popupWidth/2)+150
	});
}
function randomString() {
	var chars = "0123456789";
	var string_length = 6;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
	var rnum = Math.floor(Math.random() * chars.length);
	randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}
String.prototype.trim = function()
{
	var trimmed = this.replace(/^\s+|\s+$/g, '') ;
	return trimmed;
};
jQuery(document).ready(function() {
    jQuery("#btnAdd").live('click',function(){
        id = this.id;
        flag = "add";
        if(jQuery("#editContainer").is(":hidden")){
            setEditFormPosition(id);
            jQuery("#editContainer").slideDown("slow");
        }else{
            jQuery("#editContainer").slideUp("slow");
        }
    })
    jQuery(".editForm").live('click',function(){
        flag = "edit";
        id = this.id;
        userId = jQuery(this).parent().parent().find('td:eq(0)').html();
        username = jQuery(this).parent().parent().find('td:eq(1)').html();
        password = jQuery(this).parent().parent().find('td:eq(2)').html();
        fullname = jQuery(this).parent().parent().find('td:eq(3)').html();
        address = jQuery(this).parent().parent().find('td:eq(4)').html();
        email = jQuery(this).parent().parent().find('td:eq(5)').html();
        phone = jQuery(this).parent().parent().find('td:eq(6)').html();
        rowId = jQuery(this).parent().parent().attr('id');

        if(jQuery("#editContainer").is(":hidden")){
            setEditFormPosition(id);
            jQuery("#editContainer").slideDown("slow");

            jQuery("#txtUser").val(username);
            jQuery("#txtPass").val(password);
            jQuery("#txtFullname").val(fullname);
            jQuery("#txtAdd").val(address);
            jQuery("#txtEmail").val(email);
            jQuery("#txtPhone").val(phone);
        }else{
            jQuery("#editContainer").slideUp("slow");
        }
    });
    jQuery("#editCloseForm").click(function(){
        jQuery("#editContainer").slideUp("slow");
    });

    jQuery("#saveEdit").live('click',function(){
        rowCount = jQuery("#tblUser tr").size();
        if(flag == "edit"){
            username = jQuery("#txtUser").val();
            password = jQuery("#txtPass").val();
            fullname = jQuery("#txtFullname").val();
            address = jQuery("#txtAdd").val();
            email = jQuery("#txtEmail").val();
            phone = jQuery("#txtPhone").val();

            if(username!=null && username.length>0 && password!=null && password.length>0 && String(phone).match(compound)){
                updateUser(userId, username, password, fullname, address, email, phone, "edit");
                jQuery("#" + rowId).find('td:eq(1)').html(username);
                jQuery("#" + rowId).find('td:eq(2)').html(password);
                jQuery("#" + rowId).find('td:eq(3)').html(fullname);
                jQuery("#" + rowId).find('td:eq(4)').html(address);
                jQuery("#" + rowId).find('td:eq(5)').html(email);
                jQuery("#" + rowId).find('td:eq(6)').html(phone);
                jQuery("#editContainer").slideUp("slow");
            }else{
                alert("Username, Password can not be empty. Phone must be number");
            }
        }else if(flag == "add"){
            userID = randomString();
            
            username = jQuery("#txtUser").val();
            password = jQuery("#txtPass").val();
            fullname = jQuery("#txtFullname").val();
            address = jQuery("#txtAdd").val();
            email = jQuery("#txtEmail").val();
            phone = jQuery("#txtPhone").val();

            if(username!=null && username.length>0 && password!=null && password.length>0 && String(phone).match(compound)){
                updateUser(userID,username, password, fullname, address, email, phone, "add");
                jQuery("#tblUser").last().append(
                    "<td style='display: none;'>"+userID+"</td>"+
                    "<td>"+username+"</td>"+
                    "<td>"+password+"</td>"+
                    "<td>"+fullname+"</td>"+
                    "<td>"+address+"</td>"+
                    "<td>"+email+"</td>"+
                    "<td>"+phone+"</td>"+
                    "<td>"+
                         "<input class='editForm' id='"+rowCount+randomString+"' type='image' src='../resources/image/icn_edit.png' title='Edit'>"+
                         "<input class='delForm' id='"+rowCount+randomString+"' type='image' src='../resources/image/icn_trash.png' title='Trash'>"+
                    "</td>"
                );
                jQuery("#editContainer").slideUp("slow");
            }else{
                alert("Username, Password can not be empty. Phone must be number");
            }
        }
    });

    jQuery(".delForm").live('click',function(){
        id = this.id;
        rowId = jQuery(this).parent().parent().attr('id');
        userId = jQuery(this).parent().parent().find('td:eq(0)').html();
        username = jQuery(this).parent().parent().find('td:eq(1)').html();
        password = jQuery(this).parent().parent().find('td:eq(2)').html();
        fullname = jQuery(this).parent().parent().find('td:eq(3)').html();
        address = jQuery(this).parent().parent().find('td:eq(4)').html();
        email = jQuery(this).parent().parent().find('td:eq(5)').html();
        phone = jQuery(this).parent().parent().find('td:eq(6)').html();
        
        if(jQuery("#deleteContainer").is(":hidden")){
            setDeleteFormPosition();
            jQuery("#deleteContainer").slideDown("slow");
        }else{
            jQuery("#deleteContainer").slideUp("slow");
        }
    });

    jQuery("#noDel").live('click',function(){
        jQuery("#deleteContainer").hide("explode",1000);
    });

    jQuery("#yesDel").live('click',function(){
        id = this.id;
        updateUser(userId, username, password, fullname, address, email, phone, "delete");

        jQuery("#"+rowId).remove();

        jQuery("#deleteContainer").hide("explode",1000);
    });
});

